import os, sys

basedir = r"C:\Users\Sandesh\Desktop\TS\Studies\GSE34248"      #enter base directory

def annot(basedir, inputfile):
    """Pre: basedir is where the inputfile is.
            inputfile is the file to process.
        Post: Creates and writes data to the annotation file.
    """
    
    fa = inputfile+'_ge'
    
    f1 = open(os.path.join(basedir, fa), 'w')

    f=open(os.path.join(basedir, inputfile))
    
    afn=r"GSE34248_series_matrix.txt"                           #split to obtain study ID
    afn1 = afn.split('_')
    print afn1[0]
    
    lineprocess(f, f1)       
    f1.close()  
    f.close()

def lineprocess(f, f1):
    """Pre: f* are file handlers defined in parent def.
        Post: Write lines to file handlers.
    """

    for line in f:
        """remove all lines not containing GE data. Also remove Affymetrix probe IDs."""
        line=stripline(line)
        if line!="":
            if line[0] != '!':
                if line[:6]!='"AFFX-':
                    newline=[]   # empty list
                
                    columns=line.split("\t")
                    for c in columns:
                        if isQuoteMarks(c):
                            c=cleanQuotes(c)
                        newline.append(c)

                    tline="\t".join(newline)+"\n"    
                    f1.write(tline)

def stripline(line):
    """pre: line is a line from file
    post: return clearn line """
    
    if line[-2:]=='\r\n':
        line=line[:-2]
    elif line[-1]=='\n':
        line=line[:-1]
    elif line[-1]=='\r':
        line=line[:-1]
    else:
        line=line
    return line                

def isQuoteMarks(field):
    """pre: field is string-> need to be checked for quote on both end
    post: return true"""
    if len(field)!=0:
        if field[0]=='"':
            if field[-1]=='"':
                return True
            else:
                return False
        else:
            return False
    else:
        return False

def cleanQuotes(field):
    """Pre:
    post:   """
    return field[1:-1]

#1. Remove double quotes
#2. Add #QUAL
#3. Remove first newline character